package cn.kgc.userweb.controller;

import cn.kgc.blogcommon.pojo.User;
import cn.kgc.userweb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public String index(){
        return "login";
    }

    @RequestMapping("/goto_register")
    public String gotoRegister(){
        return "signup";
    }

    @ResponseBody
    @RequestMapping("/register")
    public Map<String, Object> register(String userPhone, String password){
        System.out.println("进入Controller...");
        User user = new User();
        Map<String, Object> map = new HashMap<>();
        if(userPhone == null || userPhone.equals("")){
            map.put("result", -1);
            map.put("message", "手机号不能为空");
        }
        if(isRepeat(userPhone)){
            map.put("result", -1);
            map.put("message", "该手机号已注册");
        }
        if(password == null || password.equals("")){
            map.put("result", -2);
            map.put("message", "密码不能为空");
        }
        if(password.length()<6){
            map.put("result", -2);
            map.put("message", "密码不能少于6位");
        }
        //MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setCreateTime(new Date());
        user.setUserPhone(userPhone);
        System.out.println(user.toString());
        //添加用户
        if(userService.register(user)){
            map.put("result", 1);
            map.put("message", "注册成功，请登录系统");
        } else {
            map.put("result", 0);
            map.put("message", "系统繁忙，请稍后重试");
        }
        return map;
    }

    public boolean isRepeat(String phone){
        return false;
    }

//    @ResponseBody
//    @RequestMapping("/login")
//    public Map<String, Object> login(){
//        Map<String, Object> result = new HashMap<>();
//
//        return null;
//    }
}
